package com.skit.ecm.search

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.skit.common.bean.ActivityBean
import com.skit.common.bean.StatusResult
import com.skit.common.config.RetrofitClient
import com.skit.common.config.RouteConfig
import com.skit.common.http.HttpUtils
import com.skit.common.utils.ToastUtils
import com.skit.ecm.search.databinding.SearchFragmentLayoutBinding
import com.skit.main.adapter.MainActivityRecyclerViewAdapter
import com.skit.common.retrofit.ActivityProtocol
import kotlinx.android.synthetic.main.search_fragment_layout.*
import retrofit2.Call
import java.util.ArrayList

class SearchFragment : Fragment() {
    private lateinit var activityAdapter: MainActivityRecyclerViewAdapter
    private val activityList: MutableList<ActivityBean> = ArrayList()
    private lateinit var binding: SearchFragmentLayoutBinding

    companion object {
        fun newInstance(): SearchFragment {
            val args = Bundle()
            val fragment = SearchFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = SearchFragmentLayoutBinding.inflate(inflater, container, false)
        binding.root.setOnClickListener { }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activityAdapter = MainActivityRecyclerViewAdapter(activityList)
        activityAdapter.onItemClickListener = object : (View, Int) -> Unit {
            override fun invoke(p1: View, p2: Int) {
                ARouter.getInstance().build(RouteConfig.MainRoute.MAIN_ACTIVITY_DETAILS)
                    .withSerializable("bean", activityList[p2])
                    .navigation()
            }
        }
        cancel.setOnClickListener {
            hideKeyboard(it)
            activity?.onBackPressed();
        }
        search_edit_text.post {
            search_edit_text.requestFocus()
            showKeyboard(search_edit_text)
        }//, 500)

        search_edit_text.setOnEditorActionListener { v, actionId, event ->
            getData(search_edit_text.text.toString())
            false
        }

        recyclerView.apply {
            adapter = activityAdapter
            layoutManager = LinearLayoutManager(activity)
        }
    }

    private fun hideKeyboard(v: View) {
        val imm: InputMethodManager = v.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
            imm.hideSoftInputFromWindow(v.applicationWindowToken, 0)
        }
    }

    private fun showKeyboard(v: EditText) {
        val imm: InputMethodManager = v.context
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        if (imm.isActive) {
            imm.showSoftInput(v, 0)
        }
    }


    private fun getData(name: String) {
        if (name.isEmpty()) {
            ToastUtils.showToast("内容为空")
            return
        }
        val userProtocol: ActivityProtocol = RetrofitClient.getService(ActivityProtocol::class.java)
        val call: Call<StatusResult<List<ActivityBean>>> =
            userProtocol.searchActivityByName(10, 10, name)
        HttpUtils.doRequest(call) {
            if (it == null) {
                ToastUtils.showToast("请求失败")
                return@doRequest
            }
            if (it.isSuccess) {
                activityList.clear()
                activityList.addAll(it.data)
                if (activityList.isEmpty()) {
                    binding.flEmptyContainer.visibility = View.VISIBLE
                    binding.tvEmpty.text = "未找到与'${name}'相关的内容"
                } else {
                    binding.flEmptyContainer.visibility = View.GONE
                }
                activityAdapter.notifyDataSetChanged()
            }
        }
    }
}